<script setup lang="ts">
import { ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { uploadAvatar } from '@/api/user'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()

const avatarUrl = ref<string>(userStore.userInfo?.avatar || '')
const loading = ref(false)

// 上传头像
const handleAvatarUpload = async (file: File) => {
  try {
    loading.value = true
    const response = await uploadAvatar(file)
    avatarUrl.value = response.data
    if (!userStore.userInfo?.userId) {
      throw new Error('用户ID不存在')
    }
    userStore.setUserInfo({
      ...userStore.userInfo,
      avatar: avatarUrl.value,
      userId: String(userStore.userInfo.userId)
    })
    ElMessage.success('头像上传成功')
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error('上传头像失败')
  } finally {
    loading.value = false
  }
}

// 处理文件上传
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }

  handleAvatarUpload(file)
  return false // 阻止自动上传
}
</script>

<template>
  <div class="avatar-container">
    <el-card>
      <template #header>
        <div class="header">
          <span>修改头像</span>
        </div>
      </template>

      <div class="avatar-uploader">
        <el-upload
          class="avatar-upload"
          action="#"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :auto-upload="false"
          accept="image/jpeg,image/png"
        >
          <el-avatar :size="150" :src="avatarUrl">
            {{ userStore.userInfo?.nickname?.charAt(0) || 'U' }}
          </el-avatar>
          <template #tip>
            <div class="el-upload__tip">
              请上传 JPG/PNG 格式的图片，大小不超过 2MB
            </div>
          </template>
        </el-upload>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.avatar-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.avatar-upload {
  text-align: center;
}

.el-upload__tip {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}
</style>
